package com.bwie.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.GoodsMapper;
import com.bwie.pojo.Goods;
import com.bwie.service.GoodsService;
import com.bwie.unit.MessageVo;
import com.bwie.unit.R;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.Mergeable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class ListController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("goodsList")
    public R goodsList(@RequestBody Goods goods){
        Page<Goods> goodsPage = new Page<>(goods.getPageNum(),goods.getPageSize());
        Page<Goods> page = goodsService.pageList(goodsPage);
        return R.OK(page);
    }

    @PostMapping("addGoods")
    private R addGoods(@RequestBody Goods goods){
        goodsService.save(goods);

        MessageVo messageVo = new MessageVo();
        String msgId = UUID.randomUUID().toString();
        messageVo.setMsgId(msgId);
        messageVo.setMsgBody(String.valueOf(goods));
        stringRedisTemplate.opsForValue().set(msgId, String.valueOf(goods),15, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend("directExchange","add", JSON.toJSONString(messageVo));
        return R.OK();
    }

    @RabbitListener(queues = "addQueue")
    public void queue(String msg, Message message, Channel channel) throws IOException {
        MessageVo messageVo = JSON.parseObject(msg, MessageVo.class);
        String msgId = messageVo.getMsgId();
        if (!stringRedisTemplate.hasKey(msgId)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
            return;
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        stringRedisTemplate.delete(msgId);
        return;
    }

}
